<template>
	<view :class="['qn-page-' + theme]" class="page-contanier">
		<view class="confirm_box">
			<view class="address-bg primary-bg"></view>
			<block v-if="JSON.stringify(order_detail) !== '{}'">
				<!-- 地址 -->
				<view class="main-view-box" style="background-color: #FFFFFF;">
					<view class="delivery-ul">
						<view class="delivery-li" @click="deliveryChange(item)" v-for="(item, index) in delivery"
							:key="index" :class="[deliveryType === item.id ? 'delivery-on' : '']">
							<text>{{ item.title }}</text>
							<view class="check-bg">{{ item.title }}</view>
						</view>
					</view>
					<view @click="goPage('/pagesT/address/address?source=1')" class="address-section "
						v-if="deliveryType === 1 || deliveryType === 3">
						<view class="order-content">
							<text class="ibonfont ibondizhi2"></text>
							<view v-if="addressData" class="cen">
								<view class="top">
									<text class="name">{{ addressData.name }}</text>
									<text class="mobile">{{ addressData.mobile }}</text>
								</view>
								<text
									class="address">{{ addressData.provinceName }}{{ addressData.cityName }}{{ addressData.districtName }}{{ addressData.address }}</text>
							</view>
							<text v-if="addressData" class="ibonfont ibonjinru"></text>
							<view v-else class="empty-tips">
								<view class="navigator primary-color">去添加收货地址></view>
							</view>
						</view>
						<view class="wu-reminder" v-if="deliveryType === 3">{{ wu_reminder }}</view>
						<image class="a-bg"
							src="">
						</image>
					</view>
					<view class="address-section " v-else-if="deliveryType === 2">
						<view class="order-content" @click="openShopPop">
							<text class="ibonfont ibondizhi2"></text>
							<view v-if="self_express_rule" class="cen">
								<view class="top">
									<text class="name">{{ self_express_rule.name }}</text>
									<text class="mobile">{{ self_express_rule.mobile }}</text>
								</view>
								<view class="top">
									<text class="name" v-if="self_express_rule.startTime && self_express_rule.endTime">
										营业时间：{{ self_express_rule.startTime }}-{{ self_express_rule.endTime }}
									</text>
									<text class="name" v-else>营业时间：全天</text>
									<text class="mobile">{{ self_express_rule.day.join(',') }}</text>
								</view>
								<text class="address">
									{{ self_express_rule.provinceName }}{{ self_express_rule.cityName }}{{ self_express_rule.districtName }}{{ self_express_rule.address }}
								</text>
							</view>
							<text v-if="self_express_rule" class="ibonfont ibonjinru"></text>
							<view class="empty-tips" v-else>
								<view class="navigator primary-color">
									<text style="font-size: 32upx; margin-right: 10upx;">+</text>
									<text>选择自提点</text>
								</view>
							</view>
						</view>
						<image class="a-bg"
							src="">
						</image>
					</view>
				</view>

				<view class="goods-section main-view-box" v-for="(item, index) in goodsData" :key="index">
					<view class="g-header b-b">
						<image class="logo" :src="item.shopLogo" mode="aspectFit"></image>
						<text class="name">{{ item.shopName }}</text>
					</view>
					<!-- 商品列表 -->
					<view class="g-item" v-for="(itemS, indexS) in item.shopGoodsData"
						@click="goPage(`/pagesT/product/product?id=${itemS.goodsId}`)" :key="indexS">
						<image :src="itemS.goodsImages" mode="aspectFill"
							:style="{ opacity: itemS.notExpress === 4 ? '0.6' : '1' }"></image>
						<view class="right">
							<view class="price-box clearfix">
								<view class="title" :style="{ color: itemS.notExpress === 4 ? '#999999' : '#333333' }">
									{{ itemS.goodsName }}
								</view>
							</view>
							<view class="price-box clearfix">
								<view class="spec float_left">
									<text>{{ itemS.unitName }}</text>
									<block v-for="(itemU, indexU) in itemS.specGroup" :key="indexU">
										<!-- style="padding-left: 4upx;" -->
										<text>_{{ itemU.specValueName }}</text>
									</block>
								</view>
								<view class="number float_right">x {{ itemS.buyNum }}</view>
							</view>
							<view class="price-box clearfix">
								<view class="float_left notExpress-tip" v-if="itemS.notExpress === 4">
									抱歉，该商品在您当前收货地址内已无库存</view>
								<view class="price float_right primary-color" v-if="itemS.notExpress === 5">
									￥{{ itemS.price }}</view>
							</view>
						</view>
					</view>
					<!-- <view class="total-view">
						小计：
						<text class="price">
							<span class="icon-rmb">¥</span>
							{{ item.totalMoney }}
						</text>
					</view> -->
				</view>
				<!-- 会员卡 -->
				<view class="yt-list main-view-box" v-if="vipList.length && JSON.stringify(vipCardList) !== '{}'">
					<view class="yt-list-cell b-b" @click="chooseVip(true)">
						<view class="cell-icon">卡</view>
						<text class="cell-tit clamp">会员卡</text>
						<text class="cell-tip active primary-color" v-if="vipName">{{ vipName }}</text>
						<text class="cell-tip active primary-color" v-else>选择会员卡</text>
						<text class="cell-more wanjia wanjia-gengduo-d"></text>
					</view>
					<view class="yt-list-cell b-b" v-if="false">
						<view class="cell-icon hb">减</view>
						<text class="cell-tit clamp">商家促销</text>
						<text class="cell-tip disabled">暂无可用优惠</text>
					</view>
				</view>
				<!-- 优惠明细 -->
				<view class="yt-list main-view-box" v-if="couponList.length">
					<view class="yt-list-cell b-b" @click="toggleMask(true)">
						<view class="cell-icon">券</view>
						<text class="cell-tit clamp">优惠券</text>
						<text class="cell-tip active primary-color"
							v-if="coupon_price > 0">-￥{{ order_detail.preferential }}</text>
						<text class="cell-tip active primary-color" v-else>选择优惠券</text>
						<text class="cell-more wanjia wanjia-gengduo-d"></text>
					</view>
					<view class="yt-list-cell b-b" v-if="false">
						<view class="cell-icon hb">减</view>
						<text class="cell-tit clamp">商家促销</text>
						<text class="cell-tip disabled">暂无可用优惠</text>
					</view>
				</view>

				<!-- 金额明细 -->
				<view class="yt-list main-view-box">
					<view class="yt-list-cell b-b">
						<text class="cell-tit clamp">商品金额</text>
						<text class="cell-tip">￥{{ order_detail.totalMoney || 0 }}</text>
					</view>
					<view class="yt-list-cell b-b">
						<text class="cell-tit clamp">优惠金额</text>
						<text class="cell-tip primary-color">-￥{{ order_detail.preferential || 0 }}</text>
					</view>
					<view class="yt-list-cell b-b">
						<text class="cell-tit clamp">会员卡折扣</text>
						<text class="cell-tip primary-color">- {{ order_detail.vipDiscount || 0 }}元</text>
					</view>
					<view class="yt-list-cell b-b" v-if="deliveryType === 1">
						<text class="cell-tit clamp">运费</text>
						<text class="cell-tip primary-color">￥{{ order_detail.expressMoney || 0 }}</text>
					</view>
					<view class="yt-list-cell desc-cell">
						<text class="cell-tit">买家留言</text>
						<input class="desc" type="text" v-model="orderRemark" placeholder="请输入留言信息给卖家"
							placeholder-class="placeholder-class" />
					</view>
				</view>
			</block>
		</view>
		<!-- 底部 -->
		<view class="footer">
			<!-- <view class="not-express-tip" v-if="!is_notExpress">抱歉，您当前订单有商品不在配送范围内，请重新调整商品后下单</view> -->
			<view class="footer-in">
				<view class="price-content">
					<text style="font-size: 26upx;color: #666;">实付:</text>
					<text class="price-tip rmb-icon">￥</text>
					<text class="price primary-color">{{ payMoney }}</text>
				</view>
				<view class="submit primary-btn" @click="selPayFun">提交订单</view>
			</view>
		</view>
		<u-popup v-model="payPop" mode="bottom" :border-radius="12">
			<view class="pay-pop-view">
				<view class="pay-sel-title clearfix">
					<text class="float_left">付款方式</text>
					<text class="float_right ibonfont ibonguanbi" @click="closePayPop"></text>
				</view>
				<view class="pay-ul">
					<block v-for="(item, index) in payment" :key="index">
						<view v-if="item.id === 7" class="pay-li" @click="paymentChange(item)">
							<text class="ibonfont ibonhuodaofukuan"></text>
							<view class="pay-name clearfix"
								:class="[order_detail.payMoney > Number(order_detail.memberBalance) ? 'balance-pay-name' : '']">
								<view class="float_left">
									<text>{{ item.title }}</text>
									<text class="balace-num">（余额:¥{{ Number(order_detail.memberBalance) }}）</text>
								</view>
								<text v-if="Number(order_detail.memberBalance) > 0"
									class="float_right ibonfont primary-color"
									:class="[payId.indexOf(item.id) > -1 ? 'ibonxuanze1' : 'ibonweixuanze']"></text>
								<text v-else class="float_right ibonfont ibonxuanze1" style="color: #CCCCCC;"></text>
								<view v-if="order_detail.payMoney > Number(order_detail.memberBalance)"
									class="balance-tip primary-color">可支付余额不足，请搭配其他支付方式</view>
							</view>
						</view>
						<view v-else class="pay-li" @click="paymentChange(item)">
							<text class="ibonfont ibonweixinzhifu" v-if="item.title.indexOf('微信') !== -1"></text>
							<text class="ibonfont ibonumidd17" v-else-if="item.title.indexOf('支付宝') !== -1"></text>
							<text class="ibonfont ibonhuodaofukuan" v-else></text>
							<view class="pay-name clearfix">
								<text class="float_left">{{ item.title }}</text>
								<text class="float_right ibonfont primary-color"
									:class="[payId.indexOf(item.id) > -1 ? 'ibonxuanze1' : 'ibonweixuanze']"></text>
							</view>
						</view>
					</block>
				</view>
				<view class="pay-btn primary-btn" @click="submit">
					<u-loading :show="sub_loading" color="#ffffff" mode="flower"></u-loading>
					<text>确定</text>
				</view>
			</view>
		</u-popup>
		<!-- 自提店 -->
		<u-popup v-model="shopPop" mode="bottom" :border-radius="12">
			<view class="self-shop-title clearfix">
				<text class="float_left">自提点</text>
				<text class="float_right ibonfont ibonguanbi" @click="closeShopPop"></text>
			</view>
			<view class="self-shop-ul">
				<view class="self-shop-li" v-for="(item, index) in order_detail.selfExpressRule" :key="index"
					@click="changeSelShop(item)">
					<view class="name">{{ item.setData.name }} {{ item.setData.mobile }}</view>
					<view>营业时间：{{ item.setData.startTime }}-{{ item.setData.endTime }} {{ item.setData.day.join(',') }}
					</view>
					<view>
						{{ item.setData.provinceName }}{{ item.setData.cityName }}{{ item.setData.districtName }}{{ item.setData.address }}
					</view>
					<text class="ibonfont sel-tag primary-color"
						:class="[selfRuleId === item.id ? 'ibonxuanze1' : 'ibonweixuanze']"></text>
				</view>
				<view class="close-btn primary-btn" @click="closeShopPop">取消</view>
			</view>
		</u-popup>
		<!-- 优惠券面板 -->
		<CouponView v-if="couponList.length" @selCoupon="selCoupon" @dontUse="dontUse" :maskState="maskState"
			:discountList="couponList" />
		<!-- 会员卡面板 -->
		<VipView v-if="vipList.length" @selvip="selvip" @dontUse="dontUseVip" :maskState="vipState"
			:vipList="vipList" />
		<!-- 余额支付密码弹窗 -->
		<u-keyboard default="" ref="uKeyboard" mode="number" :mask="true" :mask-close-able="false" :dot-enabled="false"
			v-model="pwd_show" :safe-area-inset-bottom="true" :tooltip="false" @change="balancePopChange"
			@backspace="onBackspace">
			<view>
				<view class="u-text-center u-padding-20 balance-money">
					<text v-if="payId.length > 1">{{ order_detail.memberBalance }}</text>
					<text v-else>{{ payMoney }}</text>
					<text class="u-font-20 u-padding-left-10">元</text>
					<view class="u-padding-10 close" data-flag="false" @tap="balanceShowPop(false)">
						<u-icon name="close" color="#333333" size="28"></u-icon>
					</view>
				</view>
				<view class="u-flex u-row-center">
					<u-message-input mode="box" :maxlength="6" :dot-fill="true" v-model="balance_pwd"
						:disabled-keyboard="true" @finish="balanceFinish"></u-message-input>
				</view>
				<view class="u-text-center u-padding-top-10 u-padding-bottom-20 tips">支付键盘</view>
			</view>
		</u-keyboard>
		<!-- 提示去设置支付密码 -->
		<u-modal v-model="tip_show" content="抱歉,您未设置支付密码,无法使用余额支付" :show-cancel-button="true" confirm-text="立即设置"
			cancel-text="取消" @confirm="setPassword"></u-modal>
	</view>
</template>

<script>
	import CouponView from '../components/coupon/CouponView.vue';
	import VipView from '../components/coupon/VipView.vue';
	export default {
		components: {
			CouponView,
			VipView
		},
		computed: {
			payMoney() {
				return this.order_detail.payMoney || 0;
			},
			userInfo() {
				return this.$store.state.userStatus;
			}
		},
		data() {
			return {
				wu_reminder: '',
				tip_show: false, // 余额支付提示
				pwd_show: false, // 余额支付密码输入弹窗
				balance_pwd: '', // 余额支付密码
				bank_data: {
					// 银行信息
					id: '',
					name: '',
					bankName: '',
					accountNumber: '',
					image: ''
				},
				sub_loading: false,
				payPop: false, //付款方式弹窗
				shopPop: false, //自提点弹窗
				is_notExpress: true, //商品是否都在配送范围内
				couponList: [], // 优惠券列表
				// 优惠券id
				userCouponId: '',
				maskState: false, //优惠券面板显示状态
				vipState: false,
				orderRemark: '', //备注
				coupon_price: 0, //优惠券金额
				addressData: '', // 收货地址
				self_express_rule: '', // 自提点数据
				delivery: [],
				deIndex: 0,
				goodsData: [],
				payment: [],
				payIndex: 0,
				order_detail: {
					selfExpressRule: []
				},
				source: 3,
				payId: [],
				deliveryType: '',
				delivery_title: '',
				selfRuleId: '', //自提点id
				sub_pramas: {},
				useCoupon: {},
				vipList: '',
				vipName: '',
				//跳转选择会员卡
				// vipSel: '',
				vipCardId: 0,
				vipDiscount: '',
				vipDoubleDiscount: '',
				preferential: '', //优惠金额
				location_lon: '',
				location_lat: '',
				vipCardList: [],
				buy_params: {}, //立即购买参数
				orderId: 0,
				goods_buy_obj: {},
				tmplIds: [],
				other_tmplIds: []
			};
		},
		async onLoad(options) {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.theme === 'red' ? '#f2242c' : this.primaryColor
			});
			this.source = this.$common.source();
			await this.orderVipCard();
			if (options.params) {
				this.buy_params = JSON.parse(options.params);
			} else if (options.skuId) {
				this.goods_buy_obj = options;
				console.log(this.goods_buy_obj);
			}
			await this.confirmationOfOrder();
			// #ifdef MP-WEIXIN
			await this.getSettingDataByMessageId();
			// #endif
		},
		onShow() {
			if (this.addressData !== '') {
				this.addressData = {
					...this.addressData,
					provinceName: this.addressData.area.provinceName,
					cityName: this.addressData.area.cityName,
					districtName: this.addressData.area.districtName
				};
				this.confirmationOfOrder();
			}
		},
		methods: {
			// 复制到剪贴板
			copyData(data) {
				uni.setClipboardData({
					data: data,
					success: () => {
						this.$u.toast('已复制到剪贴板');
					}
				});
			},
			// 上传银行凭证
			uploadSuccess(imgData, uploadPicUrl) {
				this.bank_data.image = uploadPicUrl;
			},
			// 打开选择自提点弹窗
			openShopPop() {
				this.shopPop = true;
			},
			closeShopPop() {
				this.shopPop = false;
			},
			// 切换自提点
			changeSelShop(row) {
				this.self_express_rule = row.setData;
				this.selfRuleId = row.id;
				this.closeShopPop();
			},
			// 获取会员卡
			async orderVipCard() {
				await this.$u.api.orderVipCard().then(({
					data
				}) => {
					this.vipCardList = data;
					this.vipCardId = data.id || 0;
					this.vipName = data.name;
				});
			},
			//显示优惠券面板
			toggleMask(type) {
				this.maskState = !!type;
			},
			//不使用优惠
			dontUse() {
				this.toggleMask(false);
				this.userCouponId = 0;
				this.coupon_price = 0;
				this.confirmationOfOrder();
			},
			// 选择会员卡
			chooseVip(type) {
				this.vipState = !!type;
			},
			// 不使用优惠券
			dontUseVip() {
				this.chooseVip(false);
				this.vipName = '';
				this.order_detail.vipDiscount = 0;
				this.vipCardId = 0;
				this.vipDiscount = this.vipDoubleDiscount || 0;
				this.confirmationOfOrder();
			},
			// 选择会员卡
			selvip(row) {
				this.vipState = false;
				this.vipName = row.name;
				this.vipCardId = row.vipCardId;
				this.confirmationOfOrder();
			},
			// 选择优惠券
			selCoupon(row) {
				this.userCouponId = row.id;
				this.toggleMask(false);
				// this.coupon_price = row.reducePrice;
				if (this.order_detail.payMoney > row.reducePrice) {
					this.coupon_price = row.reducePrice;
				} else {
					this.coupon_price = this.order_detail.payMoney;
				}
				this.confirmationOfOrder();
			},
			// 切换配送方式
			deliveryChange(item) {
				this.deliveryType = item.id;
				this.delivery_title = item.title;
				this.confirmationOfOrder();
			},
			// 切换付款方式
			paymentChange(item) {
				if (item.id === 7 && Number(this.order_detail.memberBalance) <= 0) {
					this.$u.toast('抱歉，您的可用余额不足');
				} else {
					// 已选择过该支付方式就把支付方式从数组去掉
					const payIndex = this.payId.indexOf(item.id);
					if (payIndex > -1) {
						this.payId.splice(payIndex, 1);
						return;
					}
					// 用户可支付余额不足
					if (this.order_detail.payMoney > Number(this.order_detail.memberBalance)) {
						// 查找余额支付的支付方式ID
						const balaceObj = this.payment.find(item => item.id === 7);
						// 已选择过余额支付，可选择其他支付
						const balaceindex = balaceObj ? this.payId.indexOf(balaceObj.id) : -1;
						if (balaceObj && balaceindex > -1) {
							//余额付款只能和微信支付做组合支付
							if (item.id !== 1) {
								this.payId = [item.id];
								return;
							}

							if (this.payId.length >= 2) {
								if (balaceindex === 0) {
									this.$set(this.payId, 1, item.id);
								} else {
									this.$set(this.payId, 0, item.id);
								}
							} else {
								this.payId.push(item.id);
							}
						} else {
							// 未选择余额支付,当支付数组length未0，直接把支付方式放入数组
							if (this.payId.length === 0) {
								this.payId.push(item.id);
							} else {
								//余额付款只能和微信支付做组合支付
								if (this.payId.indexOf(1) === -1) {
									//  替换 之前选择的支付方式
									this.payId.splice(0, 1, item.id);
								} else {
									// 如果当前选择的支付方式是余额支付，则放入数组
									if (item.id === 7) {
										this.payId.push(item.id);
									} else {
										// 否则 替换 之前选择的支付方式
										this.payId.splice(0, 1, item.id);
									}
								}
							}
						}
					} else {
						this.$set(this.payId, 0, item.id);
					}
				}
			},
			getOrderDetail(data) {
				this.order_detail = data;

				// 收货地址
				if (!this.addressData.id) {
					this.addressData = JSON.stringify(data.address) === '{}' ? '' : data.address;
				}
				//自提点
				if (!this.selfRuleId && data.selfExpressRule.length) {
					this.self_express_rule = data.selfExpressRule[0].setData;
					this.selfRuleId = data.selfExpressRule[0].id;
				}
				this.delivery = data.delivery;
				const wuData = this.delivery.find(item => item.deliveryType === 3);
				this.wu_reminder = wuData && wuData.setData ? wuData.setData.reminder : '';

				this.vipDiscount = data.vipDiscount;
				this.vipDoubleDiscount = data.vipDoubleDiscount;
				this.preferential = data.preferential;
				this.goodsData = data.goodsData;
				this.couponList = data.coupon;
				this.vipList = data.vipCard;
				this.useCoupon = this.order_detail.useCoupon;
				// 支付方式
				let payment = [];
				if (data.payment) {
					if (Array.isArray(data.payment)) {
						payment = data.payment;
					} else {
						payment = Object.values(data.payment);
					}
				}
				this.payment = payment.filter(item => item.title.indexOf('支付宝') === -1);
				if (!this.payId.length) {
					const payIndex = this.payment.findIndex(item => item.defaultStatus === 5);
					if (payIndex > -1) {
						if (parseInt(this.payment[payIndex].id) === 7 && this.order_detail.memberBalance <= 0) {
							this.payId = [];
						} else {
							this.payId = payIndex > -1 ? [this.payment[payIndex].id] : [];
						}
					}
				}

				// 银行信息
				/*const banck_data = data.payment.find(item => item.id === 4);
					this.bank_data =
							banck_data && banck_data.accountData
									? {
										id: banck_data.accountData.id,
										name: banck_data.accountData.name,
										bankName: banck_data.accountData.bankName,
										accountNumber: banck_data.accountData.accountNumber,
										image: ''
									}
									: {};*/

				// 配送方式
				if (!this.deliveryType) {
					const deIndex = this.delivery.findIndex(item => item.defaultStatus === 5);
					this.deliveryType = deIndex > -1 ? this.delivery[deIndex].id : this.delivery[0].id;
					this.delivery_title = deIndex > -1 ? this.delivery[deIndex].title : this.delivery[0].title;
				}

				// 验证商品是否在配送范围内
				data.goodsData.forEach(item => {
					item.is_notExpress = item.shopGoodsData.every(itemS => itemS.notExpress === 5);
				});
				this.is_notExpress = data.goodsData.every(item => item.is_notExpress);
				this.sub_pramas = {
					orderRemark: this.orderRemark,
					receiveAddressId: this.addressData.id,
					source: this.source,
					payType: this.payId,
					selfRuleId: this.selfRuleId,
					deliveryType: this.deliveryType,
					goodsData: {
						totalMoney: data.totalMoney,
						payMoney: data.payMoney,
						expressMoney: data.expressMoney,
						preferential: data.preferential,
						checkNum: data.checkNum,
						cartNum: data.cartNum,
						goodsData: data.goodsData
					}
				};
			},
			// 立即购买
			buyNow() {
				this.$u.api
					.buyNow({
						...this.buy_params,
						deliveryId: this.deliveryType,
						addressId: this.addressData.id
					})
					.then(({
						data
					}) => {
						this.getOrderDetail(data);
					});
			},
			// 商品立即购买
			goodsBuyNow() {
				this.$u.api
					.goodsBuyNow({
						...this.goods_buy_obj,
						vipCardId: this.vipCardId,
						couponId: this.userCouponId,
						addressId: this.addressData.id,
						deliveryId: this.deliveryType
					})
					.then(({
						data
					}) => {
						this.getOrderDetail(data);
					});
			},
			// 确认订单
			async confirmationOfOrder() {
				if (this.buy_params.comBinId) {
					await this.buyNow();
				} else if (this.goods_buy_obj.skuId) {
					await this.goodsBuyNow();
				} else {
					await this.confirmOrder();
				}
			},
			async confirmOrder() {
				await this.$u.api
					.confirmationOfOrder({
						userCouponId: this.userCouponId,
						vipCardId: this.vipCardId,
						deliveryId: this.deliveryType,
						addressId: this.addressData.id
					})
					.then(({
						data
					}) => {
						this.getOrderDetail(data);
					});
			},
			selPayFun() {
				if (!this.is_notExpress) {
					return;
				}
				this.payPop = true;
			},
			closePayPop() {
				this.payPop = false;
			},
			// 提交订单
			submit() {
				if (!this.is_notExpress) {
					return;
				}
				// 验证账户状态
				this.userAudit();
				if (!this.isUserAudit) {
					return;
				}

				if (!this.payId.length) {
					this.$api.msg('请选择支付方式');
					return;
				}
				if (this.order_detail.payMoney > Number(this.order_detail.memberBalance)) {
					if (this.payId.indexOf(7) > -1 && this.payId.length !== 2) {
						this.$api.msg('可支付余额不足，请搭配其他支付方式');
						return;
					}
				}
				if (!this.deliveryType) {
					this.$api.msg('请选择配送方式');
					return;
				}
				if (this.delivery_title.indexOf('自提') === -1) {
					if (!this.addressData) {
						this.$api.msg('请选择收货地址');
						return;
					}
				}
				// 余额支付弹窗
				if (this.payId.indexOf(7) > -1 && Number(this.order_detail.memberBalance) > 0) {
					if (this.userInfo.payPassword) {
						this.balanceShowPop();
					} else {
						this.tip_show = true;
					}
					return;
				}
				this.addOrder();
			},
			addOrder() {
				// #ifdef MP-WEIXIN
				if (this.tmplIds.length) {
					uni.requestSubscribeMessage({
						tmplIds: this.tmplIds,
						success: res => {
							this.createOrder();
						},
						fail: res => {
							console.log(res);
							this.createOrder();
						}
					});
				} else {
					this.createOrder();
				}
				// #endif
				// #ifdef APP-PLUS||H5
				this.createOrder();
				// #endif
			},
			// 订单审核，取消订单提醒
			otheMsgTip(url) {
				uni.redirectTo({
					url: url
				});
				return;
				uni.requestSubscribeMessage({
					tmplIds: this.other_tmplIds,
					success: res => {
						uni.redirectTo({
							url: url
						});
					},
					fail: res => {
						console.log(res);
						uni.redirectTo({
							url: url
						});
					}
				});
			},
			createOrder() {
				const goodsData = {
					...this.sub_pramas.goodsData,
					vipDiscount: this.vipDiscount || 0,
					vipDoubleDiscount: this.vipDoubleDiscount || 0,
					preferential: this.preferential || 0
				};

				// 余额支付数据
				let admixPayData = [];
				let payType = '';
				if (this.payId.length === 2) {
					// 查找余额支付的支付方式ID
					const balaceObj = this.payment.find(item => item.id === 7);
					admixPayData = this.payId.map(item => {
						let obj = {};
						if (balaceObj.id === item) {
							obj = {
								payType: item,
								title: balaceObj.title,
								payMoney: Number(this.order_detail.memberBalance)
							};
						} else {
							obj = {
								payType: item,
								title: this.payment.find(pay => pay.id === item).title,
								payMoney: this.$NP.minus(this.payMoney, this.order_detail.memberBalance)
							};
						}

						return obj;
					});
					payType = this.payId.join(',');
				} else if (this.payId.length === 1) {
					payType = parseInt(this.payId[0]);
				}
				// console.log(admixPayData);
				// return;
				let params = {
					...this.sub_pramas,
					goodsData: goodsData,
					receiveAddressId: this.addressData.id || 0,
					source: this.source,
					payType: payType,
					selfRuleId: this.selfRuleId,
					deliveryType: this.deliveryType,
					orderRemark: this.orderRemark,
					useCoupon: this.useCoupon,
					admixPayData: admixPayData
				};
				// if (this.payId.indexOf(4) > -1) {
				// 	params.bankData = this.bank_data;
				// }
				if (this.buy_params) {
					params.comBinId = this.buy_params.comBinId;
				}

				if (this.sub_loading) {
					return;
				}
				this.sub_loading = true;
				this.$u.api
					.addOrder(params)
					.then(data => {
						this.sub_loading = false;
						// 如果是支付宝支付，返回的data是一串字符串
						this.closePayPop();
						// 创建订单成功添加分销上下级关系
						this.relationshipBusinessman(2);
						// 货到付款 直接进入订单页面
						if (this.payId.indexOf(3) > -1) {
							// 订单审核，取消订单提醒
							this.otheMsgTip('/pagesT/order/order?state=0');
							return;
						} else if (this.payId.indexOf(4) > -1) {
							// 银行打款
							const orderId = data.data;
							// 订单审核，取消订单提醒
							this.otheMsgTip(`/pagesT/money/BankPay?orderId=${orderId}&payAmount=${this.payMoney}`);
							return;
						}
						if (JSON.stringify(data.data) === '{}') {
							this.otheMsgTip('/pagesT/order/order?state=0');
							return;
						}
						// 获取提交支付数据
						const payInfo = data.data;
						console.log('payInfo', payInfo);
						// app 支付
						// #ifdef APP-PLUS
						let provider = '';
						if (this.payId.indexOf(1) > 1) {
							provider = 'wxpay';
						} else if (this.payId.indexOf(2) > 1) {
							provider = 'alipay';
						}
						uni.requestPayment({
							provider: provider, //供应商
							orderInfo: JSON.stringify(payInfo),
							success: res => {
								setTimeout(() => {
									uni.redirectTo({
										url: '/pagesT/money/paySuccess?price=' + this
											.order_detail.payMoney
									});
								}, 100);
							},
							fail: err => {
								console.log('支付失败', err);
								this.sub_loading = false;
								setTimeout(() => {
									uni.redirectTo({
										url: '/pagesT/order/order?state=0'
									});
								}, 100);
							}
						});
						// #endif

						// #ifdef MP-WEIXIN
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: payInfo.timeStamp, //当前时间
							nonceStr: payInfo.nonceStr, //随机字符串，长度在32一下
							package: payInfo.package, //统一单接口返回的prepay_id
							signType: payInfo.signType, //签名算法，目前支持MD5
							paySign: payInfo.paySign, //签名
							success: res => {
								// 订单审核，取消订单提醒
								setTimeout(() => {
									this.otheMsgTip('/pagesT/money/paySuccess?price=' + this
										.order_detail.payMoney);
								}, 200);
							},
							fail: async err => {
								console.log('支付失败');
								await setTimeout(() => {
									uni.redirectTo({
										url: '/pagesT/order/order?state=0'
									});
								}, 100);
							}
						});
						// #endif

						// #ifdef MP-TOUTIAO
						uni.requestPayment({
							provider: 'toutiao',
							service: 3, //字节跳动小程序必填，service=3： 微信API支付，不拉起小程序收银台；service=4： 支付宝API支付，不拉起小程序收银台。
							orderInfo: payInfo,
							success: res => {
								this.$u.api
									.orderquery({
										out_trade_no: payInfo.out_order_no
									})
									.then(pay => {
										const payStatus = pay.data;
										if (payStatus === 'SUCCESS') {
											uni.redirectTo({
												url: '/pagesT/money/paySuccess?price=' + this
													.order_detail.payMoney
											});
										} else {
											uni.redirectTo({
												url: '/pagesT/order/order?state=0'
											});
										}
									});
							},
							fail: async err => {
								console.log('fail::', err);
								await setTimeout(() => {
									uni.redirectTo({
										url: '/pagesT/order/order?state=0'
									});
								}, 100);
							}
						});
						// #endif
						// #ifdef H5
						if (payInfo) {
							this.H5pay(payInfo);
						}
						// #endif
					})
					.catch(res => {
						this.sub_loading = false;
						this.balance_pwd = '';
					});
			},

			H5pay(payInfo) {
				// #ifdef H5
				const u = navigator.userAgent;
				const app = navigator.appVersion;
				const mobile = !!u.match(/AppleWebKit.*Mobile.*/); //是否为移动终端

				if (mobile) {
					const ua = navigator.userAgent.toLowerCase(); //获取判断用的对象
					if (ua.match(/MicroMessenger/i) == 'micromessenger') {
						//在微信中打开
						WeixinJSBridge.invoke(
							'getBrandWCPayRequest', {
								appId: payInfo.appId, //公众号名称，由商户传入
								timeStamp: payInfo.timeStamp, //时间戳，自1970年以来的秒数
								nonceStr: payInfo.nonceStr, //随机串
								package: payInfo.package, //订单详情扩展字符串
								signType: payInfo.signType, //微信签名方式：
								paySign: payInfo.paySign //微信签名
							},
							res => {
								if (res.err_msg == 'get_brand_wcpay_request:ok') {
									this.$u.toast('支付成功！');
									// 订单审核，取消订单提醒
									setTimeout(() => {
										this.otheMsgTip('/pagesT/money/paySuccess?price=' + this.order_detail
											.payMoney);
									}, 1500);
								} else {
									this.$u.toast('支付失败！');
									setTimeout(() => {
										uni.redirectTo({
											url: '/pagesT/order/order?state=0'
										});
									}, 1500);
								}
							}
						);
					} else {
						//在自带浏览器中打开
						window.location.replace(payInfo);
					}
				} else {
					//在pc中打开
					this.$u.toast('该系统暂不支持微信支付');
					setTimeout(() => {
						uni.redirectTo({
							url: '/pagesT/order/order?state=0'
						});
					}, 1500);
					// console.log('在pc中打开');
				}
				// #endif
			},

			// 余额支付密码键盘按键被点击(不包含退格键被点击)
			balancePopChange(val) {
				if (this.balance_pwd.length < 6) {
					this.balance_pwd += val;
				}

				if (this.balance_pwd.length >= 6) {
					// 唤起密码验证
					this.checkPayPassword();
				}
			},
			//键盘退格键被点击
			onBackspace(e) {
				if (this.balance_pwd.length > 0) {
					this.balance_pwd = this.balance_pwd.substring(0, this.balance_pwd.length - 1);
				}
			},
			// 余额密码弹窗显示
			balanceShowPop(flag = true) {
				this.balance_pwd = '';
				this.pwd_show = flag;
			},
			// 余额密码输入完成
			balanceFinish() {
				// 唤起支付
				this.addOrder();
			},
			// 添加分销上下级关系 source: 1:首次点击链接 2:首次下单 3:首次付款'
			relationshipBusinessman(source) {
				console.log('上级ID', this.$store.state.businessmanId);
				if (!this.$store.state.businessmanId) {
					return;
				}
				this.$u.api
					.relationshipBusinessman({
						businessmanId: this.$store.state.businessmanId,
						source: source
					})
					.then(res => {
						console.log('上下:', res);
					});
			},
			// 去设置支付密码
			setPassword() {
				this.goPage('/pagesT/money/PayPassword');
			},
			// 支付密码校验
			checkPayPassword() {
				uni.showLoading();
				this.$u.api
					.checkPayPassword({
						id: this.userInfo.id,
						payPassword: this.balance_pwd
					})
					.then(res => {
						this.addOrder();
					})
					.catch(res => {
						this.balance_pwd = '';
					});
			},
			// 获取消息模版ID 下单成功、发货通知、支付成功
			getSettingDataByMessageId() {
				this.$u.api
					.getSettingDataByMessageId({
						id: [1, 2, 3, 5, 6]
					})
					.then(res => {
						if (res.data.length > 0) {
							this.tmplIds = res.data
								.filter(item => [1, 2, 3].includes(item.messageId))
								.map(item => {
									return item.weixinTemplateId;
								});
							this.other_tmplIds = res.data
								.filter(item => [5, 6].includes(item.messageId))
								.map(item => {
									return item.weixinTemplateId;
								});
						}
					});
			}
		}
	};
</script>

<style lang="scss">
	body {
		background: $page-color-base;
		padding-bottom: 100upx;
	}

	.placeholder-class {
		font-size: 24upx;
		color: #999;
	}

	.total-view {
		text-align: right;
		font-size: 24upx;
		color: #999;
		padding: 10upx 24upx;

		.price {
			color: $price-color;
			font-size: 30upx;
			font-weight: bold;
		}
	}

	.confirm_box {
		width: 100%;
		padding: 1upx 18upx 0;
		background: $page-color-base;
		min-height: 100%;
		padding-bottom: 150upx;
		position: relative;

		.address-bg {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 180upx;
		}

		.delivery-ul {
			display: flex;
			margin-top: 30upx;
			line-height: 70upx;
			height: 70upx;

			.delivery-li {
				font-size: 28upx;
				background: #fef6f4;
				text-align: center;
				flex: 3;
				position: relative;

				.check-bg {
					display: none;
					position: absolute;
					top: -10upx;
					height: 80upx;
					background-color: #fff;
					width: 100%;
					background: linear-gradient(243deg, transparent 36upx, #ffffff 0);
				}
			}

			.delivery-li:nth-child(2) .check-bg {
				background: linear-gradient(110deg, transparent 30upx, #ffffff 0) top left, linear-gradient(-110deg, transparent 30upx, #ffffff 0) top right;
				background-size: 60% 100%;
				background-repeat: no-repeat;
			}

			.delivery-li:last-child .check-bg {
				background: linear-gradient(113deg, transparent 32upx, #ffffff 0);
			}

			.delivery-on {
				font-weight: bold;

				.check-bg {
					display: block;
				}
			}
		}

		.main-view-box {
			border-radius: 8upx;
			box-shadow: 0px 0px 10upx 4upx #f5f5f5;
		}

		.address-section {
			padding: 30upx 0;
			background: #fff;
			position: relative;

			.order-content {
				display: flex;
				align-items: center;
			}

			.wu-reminder {
				font-size: 24rpx;
				color: $uni-color-warning;
				padding-top: 10rpx;
				padding-left: 90rpx;
			}

			.ibonwuliu,
			.ibondizhi2 {
				flex-shrink: 0;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 90upx;
				color: #888;
				font-size: 44upx;
			}

			.cen {
				display: flex;
				flex-direction: column;
				flex: 1;
				font-size: 28upx;
				color: $font-color-dark;
			}

			.mobile,
			.name {
				font-size: 24upx;
				margin-right: 24upx;
				color: #666;
			}

			.address {
				margin-top: 10upx;
				margin-right: 20upx;
				font-size: 26upx;
				// color: $font-color-light;
			}

			.icon-you {
				font-size: 32upx;
				color: $font-color-light;
				margin-right: 30upx;
			}

			.a-bg {
				position: absolute;
				left: 0;
				bottom: 0;
				display: block;
				width: 100%;
				height: 5upx;
			}
		}
	}

	.empty-tips {
		display: flex;
		font-size: $font-sm + 2upx;
		color: $font-color-disabled;

		.navigator {
			color: $uni-color-primary;
			margin-left: 16upx;
		}
	}

	.goods-section {
		margin-top: 20upx;
		background: #fff;
		padding-bottom: 1px;

		.g-header {
			display: flex;
			align-items: center;
			height: 74upx;
			padding: 0 30upx;
			position: relative;
		}

		.logo {
			display: block;
			width: 35upx;
			height: 35upx;
			border-radius: 35upx;
		}

		.name {
			font-size: 24upx;
			color: $font-color-dark;
			margin-left: 24upx;
			font-weight: bold;
		}

		.g-item {
			display: flex;
			margin: 20upx;

			image {
				flex-shrink: 0;
				display: block;
				width: 140rpx;
				height: 140rpx;
				border-radius: 8upx;
				background-color: #f7f7f7;
			}

			.right {
				flex: 1;
				margin-left: 24upx;
				overflow: hidden;
				border-bottom: 1upx solid #f5f5f5;
			}

			.spec {
				display: inline-block;
				font-size: 24upx;
				color: #999999;
				// margin-bottom: 6upx;
				// padding: 6upx 20upx;
				// background-color: #f5f5f5;
				border-radius: 30upx;
			}

			.price-box {
				font-size: 28upx;
				color: $price-color;
				padding-bottom: 6upx;

				.notExpress-tip {
					color: #e6a23c;
					font-size: 24upx;
				}

				.title {
					font-size: 28upx;
					color: $font-color-dark;
				}

				.price {
					margin-bottom: 4upx;
					font-weight: bold;
				}

				.number {
					font-size: 24upx;
					color: $font-color-base;
				}
			}

			.step-box {
				position: relative;
			}
		}
	}

	.yt-list {
		margin-top: 20upx;
		background: #fff;
		// margin-bottom: 100upx;
	}

	.yt-list-cell {
		display: flex;
		align-items: center;
		padding: 10upx 20upx;
		line-height: 70upx;
		position: relative;

		.ibonfont {
			color: #999;
			padding-left: 10upx;
			transform: translateY(4upx);
			display: inline-block;
		}

		&.cell-hover {
			background: #fafafa;
		}

		&.b-b:after {
			left: 30upx;
		}

		.cell-icon {
			height: 32upx;
			width: 32upx;
			font-size: 22upx;
			color: #fff;
			text-align: center;
			line-height: 32upx;
			background: #f85e52;
			border-radius: 4upx;
			margin-right: 12upx;

			&.hb {
				background: #ffaa0e;
			}

			&.lpk {
				background: #3ab54a;
			}
		}

		.cell-more {
			align-self: center;
			font-size: 24upx;
			color: $font-color-light;
			margin-left: 8upx;
			margin-right: -10upx;
		}

		.cell-tit {
			flex: 1;
			font-size: 28upx;
			color: #666;
			margin-right: 10upx;
		}

		.cell-tip {
			font-size: 28upx;
			color: $font-color-dark;

			&.disabled {
				color: $font-color-light;
			}

			&.active {
				color: #f85e52;
			}

			&.red {
				color: #f85e52;
			}
		}

		&.desc-cell {
			.cell-tit {
				max-width: 116upx;
			}
		}

		.desc {
			flex: 1;
			font-size: $font-base;
			color: $font-color-dark;
			text-align: right;
		}
	}

	.footer {
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 995;
		width: 100%;
		font-size: 26upx;
		background-color: #fff;
		z-index: 9;
		color: $font-color-base;
		border-top: 1upx solid #f5f5f5;

		.not-express-tip {
			font-size: 22upx;
			background-color: #fdf6ec;
			color: #d48d24;
			text-align: center;
			line-height: 42upx;
		}

		.footer-in {
			height: 100upx;
			justify-content: space-between;
			display: flex;
			align-items: center;
		}

		.price-content {
			padding-left: 20upx;
		}

		.price-tip {
			color: $price-color;
			margin-left: 8upx;
		}

		.price {
			font-size: 48upx;
			color: $price-color;
			// font-weight: bold;
		}

		.submit {
			width: 210upx;
			height: 74upx;
			text-align: center;
			border-radius: 8upx;
			line-height: 74upx;
			margin-right: 20rpx;
			color: #fff;
			font-size: $font-base;
		}
	}

	.pay-pop-view {
		background-color: #ffffff;
		border-top-left-radius: 12upx;
		border-top-right-radius: 12upx;
		font-size: 28upx;

		.pay-sel-title {
			padding: 0 30upx;
			line-height: 88upx;
			font-weight: bold;
			font-size: 32upx;

			.ibonfont {
				color: #999;
				font-weight: 400;
			}
		}

		.pay-btn {
			height: 90upx;
			line-height: 90upx;
			color: #fff;
			font-size: 32upx;
			text-align: center;
		}

		.pay-ul {
			.pay-li {
				line-height: 100upx;

				.ibonfont {
					padding-left: 30upx;
					font-size: 46upx;
					vertical-align: middle;
					margin-right: 24upx;
				}

				.ibonweixinzhifu {
					color: #04be02;
				}

				.ibonumidd17 {
					color: #108ee9;
				}

				.ibonhuodaofukuan {
					color: #f2b844;
				}

				.pay-name {
					width: 650upx;
					display: inline-block;
					padding-right: 30upx;
					vertical-align: middle;
					border-bottom: 1px solid #f5f5f5;

					.ibonxuanze1,
					.ibonweixuanze {
						margin-right: 0;
						padding-left: 0;
						font-size: 38upx;
					}

					.balace-num {
						font-size: 24rpx;
						color: #6c6c6c;
					}
				}

				.balance-pay-name {
					position: relative;
					padding-bottom: 20rpx;

					.balance-tip {
						position: absolute;
						font-size: 22rpx;
						line-height: 36rpx;
						bottom: 10rpx;
						left: 0;
					}
				}
			}
		}
	}

	.self-shop-title {
		padding: 0 30upx;
		line-height: 88upx;
		font-weight: bold;
		font-size: 32upx;

		.ibonfont {
			color: #999;
			font-weight: 400;
		}
	}

	.self-shop-ul {
		background-color: #ffffff;
		padding: 24upx;

		.close-btn {
			width: 690upx;
			height: 80upx;
			line-height: 80upx;
			color: #fff;
			font-size: 32upx;
			text-align: center;
			margin: 20upx auto 0;
			border-radius: 10upx;
		}

		.self-shop-li {
			font-size: 24upx;
			line-height: 36upx;
			padding-bottom: 24upx;
			border-bottom: 1px solid #f5f5f5;
			margin-bottom: 24rpx;
			position: relative;

			.sel-tag {
				position: absolute;
				top: 50%;
				right: 20upx;
				transform: translateY(-50%);
				font-size: 46upx;
			}

			.name {
				font-size: 28upx;
				padding-bottom: 10upx;
			}
		}
	}

	.balance-money {
		font-size: 80rpx;
		color: $u-type-warning;
		position: relative;

		.close {
			position: absolute;
			top: 20rpx;
			right: 20rpx;
			line-height: 28rpx;
			font-size: 28rpx;
		}
	}
</style>
